package service

import (
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	cDto "tuowei.com/common/dto"
	"tuowei.com/pkg/xlog"
)

type SysCourse struct {
	service.Service
}

// GetPage 获取SysCourse列表
func (e *SysCourse) GetPage(c *dto.SysCourseGetPageReq, p *actions.DataPermission, list *[]models.SysCourseList, count *int64) error {
	var err error
	var data models.SysCourse

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).Order("course_id desc").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	return nil
}

// Insert 创建SysCourse对象
func (e *SysCourse) Insert(c *dto.SysCourseInsertReq) (int, error) {
	var err error
	var data models.SysCourse
	var model models.SysCourseGift
	//var i int64
	//err = e.Orm.Model(&data).
	//	Where("serial_num = ?", c.SerialNum).Count(&i).Error
	//if err != nil {
	//	e.Log.Errorf("db error: %s", err)
	//	return err
	//}
	//if i > 0 {
	//	err := errors.New("课程编号已存在！")
	//	e.Log.Errorf("db error: %s", err)
	//	return err
	//}

	c.Generate(&data)

	//if c.CourseWareJson != "" {
	//	var courseWare models.CourseWare
	//	err = json.Unmarshal([]byte(c.CourseWareJson), &courseWare)
	//	if err != nil {
	//		e.Log.Errorf("json unmarshal error: %s", err)
	//		return 0, err
	//	}
	//	err = e.Orm.Create(&data).Error
	//	if err != nil {
	//		e.Log.Errorf("db error: %s", err)
	//		return 0, err
	//	}
	//	courseId := data.GetId()
	//	for k, v := range courseWare {
	//		var sysCourseWare models.SysCourseWare
	//		sysCourseWare.CourseId = courseId.(int)
	//		sysCourseWare.Name = v.Name
	//		sysCourseWare.Sort = k + 1
	//		sysCourseWare.CourseWare = ""
	//		sysCourseWare.Pid = 0
	//		sysCourseWare.Level = 1
	//		err = e.Orm.Create(&sysCourseWare).Error
	//
	//		if err != nil {
	//			e.Log.Errorf("db error: %s", err)
	//			return 0, err
	//		}
	//		lastId := sysCourseWare.GetId()
	//		children := make([]models.SysCourseWare, 0)
	//		for jk, jv := range v.Children {
	//			children = append(children, models.SysCourseWare{
	//				CourseId:   courseId.(int),
	//				Name:       jv.Name,
	//				CourseWare: jv.URL,
	//				Pid:        lastId.(int),
	//				Level:      2,
	//				Sort:       jk + 1,
	//				UrlName:    jv.UrlName,
	//			})
	//		}
	//		err = e.Orm.Table(sysCourseWare.TableName()).Create(children).Error
	//
	//		if err != nil {
	//			e.Log.Errorf("db error: %s", err)
	//			return 0, err
	//		}
	//	}
	//} else {
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return 0, err
	}

	if c.Step2.CourseGift != nil {
		tmp := []models.SysCourseGift{}
		for _, v := range c.Step2.CourseGift {
			tmp = append(tmp, models.SysCourseGift{
				CourseId:   data.CourseId,
				GiftType:   v.GiftType,
				CourseType: "online",
				ObjIds:     v.ObjIds,
			})
		}
		err = e.Orm.Model(model).Create(&tmp).Error
		if err != nil {
			xlog.Error(err)
			return 0, err
		}
	}
	//}
	return data.CourseId, nil
}

func (e *SysCourse) UpdateStatus(c *dto.SysCourseUpdateStatusReq) error {
	var err error
	var model = models.SysCourse{}
	e.Orm.First(&model, c.GetId())
	c.Generate(&model)
	db := e.Orm.Save(&model)
	err = db.Error
	if err != nil {
		e.Log.Errorf("Service UpdateStatus error:%s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")

	}
	return nil
}

func (e *SysCourse) Update(c *dto.SysCourseUpdateReq) error {
	var err error
	var model = models.SysCourse{}

	var sysCourseGiftModel models.SysCourseGift
	e.Orm.First(&model, c.GetId())
	c.Generate(&model)
	return e.Orm.Transaction(func(tx *gorm.DB) error {
		err = tx.Save(&model).Error
		if err != nil {
			return err
		}
		if c.Step2.CourseGift != nil {
			for _, v := range c.Step2.CourseGift {
				// 以前的逻辑有bug。。。当gfit表里没数据的时候更新没屁用
				// 先删除gift表里的数据
				tx.Where("course_id = ?", c.GetId()).Where("gift_type = ?", v.GiftType).Delete(sysCourseGiftModel)
				// 重新插入
				err = tx.Model(sysCourseGiftModel).Create(&models.SysCourseGift{
					CourseId:   c.CourseId,
					GiftType:   v.GiftType,
					ObjIds:     v.ObjIds,
					CourseType: "online",
				}).Error
				if err != nil {
					return err
				}
			}

		}

		return nil
	})
}

// Remove 删除SysClass
func (e *SysCourse) Remove(c *dto.SysCourseById, p *actions.DataPermission) error {
	var err error
	var data models.SysCourse

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, c.GetId())
	if err = db.Error; err != nil {
		xlog.Errorf("Error found in  RemoveSysCourse : %s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// GetSysDeptList 获取组织数据
func (e *SysCourse) getList(linkId int, list *[]models.SysCourseWare) error {
	var err error
	var data models.SysCourseWare

	err = e.Orm.Model(&data).
		Where("course_id = ?", linkId).
		Find(list).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Call 递归构造组织数据
func (e SysCourse) CourseWareTreeCall(linkId int) (m []models.CourseWareTree, err error) {
	var list []models.SysCourseWare
	err = e.getList(linkId, &list)

	m = make([]models.CourseWareTree, 0)
	for i := 0; i < len(list); i++ {
		if list[i].Pid != 0 {
			continue
		}
		s := models.CourseWareTree{}
		s.Id = list[i].Id
		s.Name = list[i].Name
		s.CourseId = list[i].CourseId
		s.IsShow = list[i].IsShow
		s.Url = list[i].CourseWare
		s.IsContainExercise = -1
		deptsInfo := e.courseWareTreeCall(&list, s)
		m = append(m, deptsInfo)
	}
	return
}

// Call 递归构造组织数据
func (e SysCourse) courseWareTreeCall(deptList *[]models.SysCourseWare, result models.CourseWareTree) models.CourseWareTree {
	list := *deptList
	min := make([]models.CourseWareTree, 0)
	for j := 0; j < len(list); j++ {
		if result.Id != list[j].Pid {
			continue
		}
		mi := models.CourseWareTree{Id: list[j].Id, Name: list[j].Name, Url: list[j].CourseWare, UrlName: list[j].UrlName, IsShow: list[j].IsShow, IsContainExercise: list[j].IsContainExercise, Pid: list[j].Pid, CourseId: list[j].CourseId, Children: []models.CourseWareTree{}}
		ms := e.courseWareTreeCall(deptList, mi)
		min = append(min, ms)
	}
	result.Children = min
	return result
}

// Get 获取SysCourse对象
func (e *SysCourse) Get(d *dto.SysCourseById, p *actions.DataPermission, model *models.SysCourse) error {
	var data models.SysCourse
	var err error
	err = e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		xlog.Errorf("db error: %s", err)
		return err
	}

	model.CourseWareJson, err = e.CourseWareTreeCall(d.Id)

	if err != nil {
		xlog.Errorf("db error: %s", err)
		return err
	}

	return nil
}

func (e *SysCourse) GetBindingCourseList(list *[]models.CourseList) error {
	var model models.SysCourse
	return e.Orm.Model(model).Where("is_bind_offline = ?", 1).Find(&list).Error
}
